package com.jack.helloworld.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jack.helloworld.R;
import com.jack.helloworld.fragment.MyFragment;

import androidx.appcompat.app.AppCompatActivity;

public class FragmentValueActivity extends AppCompatActivity implements MyFragment.FragmentActivityListener {

    EditText etFragmentValue;
    Button btnFragmentValue;
    TextView tvMyFragment;

    Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_value);

        initView();
        initData();
    }

    private void initView() {
        etFragmentValue = (EditText) findViewById(R.id.etFragmentValue);
        btnFragmentValue = (Button) findViewById(R.id.btnFragmentValue);
        tvMyFragment = (TextView) findViewById(R.id.tvMyFragment);
    }

    private void initData() {

        btnFragmentValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = etFragmentValue.getText().toString();
                Bundle bundle = new Bundle();
                bundle.putString("etValue", text);

                fragment = new MyFragment();
                fragment.setArguments(bundle);
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.llFragmentValue, fragment, "myfragment");
                fragmentTransaction.commit();


                Toast.makeText(FragmentValueActivity.this, R.string.text_activity_to_fragment, Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void sendToActivityMessage(String message) {
        Toast.makeText(this, getString(R.string.text_receive_from_fragment) + message, Toast.LENGTH_SHORT).show();
        btnFragmentValue.setText(message);
    }
}
